package com.zhilianbao.leyaogo.ui.fragment.home;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;

import com.bql.convenientlog.CLog;
import com.bql.pulltorefreshandloadmore.ultraptr.PtrFrameLayout;
import com.bql.pulltorefreshandloadmore.ultraptr.indicator.PtrIndicator;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.StringUtils;
import com.bql.utils.ThreadPool;
import com.google.gson.reflect.TypeToken;
import com.melnykov.fab.FloatingActionButton;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.ActivityApi;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.api.SupplierApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.http.convert.GsonConvert;
import com.zhilianbao.leyaogo.listener.OnAddToCartClickListener;
import com.zhilianbao.leyaogo.model.response.category.GoodsInfo;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.category.SkuMapEntity;
import com.zhilianbao.leyaogo.model.response.home.BaseHomeData;
import com.zhilianbao.leyaogo.model.response.home.SpecialActivityInfo;
import com.zhilianbao.leyaogo.model.response.home.SupplierContent;
import com.zhilianbao.leyaogo.model.response.home.SupplierHome;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.activity.MainActivity;
import com.zhilianbao.leyaogo.ui.activity.home.SelectSupplierActivity;
import com.zhilianbao.leyaogo.ui.activity.search.SearchActivity;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeAppListAOne;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeAppListATwoThree;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeAppListATypeZeroInfo;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeAppListAZero;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeTopicContent;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeTopicContentViewProvider;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeTopicMore;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeTopicMoreViewProvider;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeTopicTitle;
import com.zhilianbao.leyaogo.ui.adapter.home.applista.HomeTopicTitleViewProvider;
import com.zhilianbao.leyaogo.ui.adapter.home.grids.HomeAppGrids;
import com.zhilianbao.leyaogo.ui.adapter.home.grids.HomeAppGridsViewProvider;
import com.zhilianbao.leyaogo.ui.adapter.home.magic.HomeAppMagic;
import com.zhilianbao.leyaogo.ui.adapter.home.magic.HomeAppMagicViewProvider;
import com.zhilianbao.leyaogo.ui.adapter.home.notice.HomeAppNotice;
import com.zhilianbao.leyaogo.ui.adapter.home.notice.HomeAppNoticeViewProvider;
import com.zhilianbao.leyaogo.ui.adapter.home.slider.HomeAppSlider;
import com.zhilianbao.leyaogo.ui.adapter.home.slider.HomeAppSliderViewProvider;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseMultiTypeFragment;
import com.zhilianbao.leyaogo.utils.GoodsSpecPopUtils;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.ShopAnimationUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.widgets.MyRelativeLayout;
import com.zhilianbao.okhttputils.callback.Callback;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.drakeet.multitype.MultiTypeAdapter;
import okhttp3.Call;
import okhttp3.Response;

/**
 * ClassName: HomeFragment <br>
 * Description: 首页Fragment<br>
 * Author: Cyarie <br>
 * Created: 2016/10/23 15:12 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class HomeFragment extends BaseMultiTypeFragment implements OnAddToCartClickListener<HomeTopicContent> {

    //    private String mLocation;


    //    @BindView(R.id.ll_search_zone)
    //    public LinearLayout mLlSearchZone;

    //    //搜索栏隐藏动画
    //    private TranslateAnimation mSearchGoneAnim = null;
    //    //搜索栏显示动画
    //    private TranslateAnimation mSearchShowAnim = null;
    //    //搜索栏动画是否正在执行
    //    private boolean mIsAnimating = false;

    //recyclerView header top view
    //    public View headerTopView;

    @BindView(R.id.fab)
    public FloatingActionButton mFab;

    @BindView(R.id.rl_content)
    public MyRelativeLayout mRl;

    //状态栏底部分割线
    @BindView(R.id.view_home_bottom_line)
    public View mHomeBottomLine;
    //    @BindView(R.id.stateLayout)
    //    AnimationStateTypeLayout mStateLayout;

    private MultiTypeAdapter mMultiTypeAdapter;

    private int heightArray[];

    private List<String> hotList = new ArrayList<>();

    public static HomeFragment getInstance() {
        HomeFragment homeFragment = new HomeFragment();
        return homeFragment;
    }

    private String[] titles = new String[]{"为您推荐", "限量特价", "进店必买", "每周上新", "一元抢购"};

    @Override
    protected void initToolbarHere() {
        initHomeToolbar(StringUtils.isEmpty(Utils.getLocation(), getString(R.string.locating)), "");
        mLlSearchBar.getDelegate().setBackgroundColor(getResources().getColor(R.color.color_FFFFFF_trans_70));
        if (mTvLeft != null)
            mTvLeft.setText(Utils.getLocation());
        mFab.hide(false);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mMultiTypeAdapter = new MultiTypeAdapter(mItems);
        //注册banner
        mMultiTypeAdapter.register(HomeAppSlider.class, new HomeAppSliderViewProvider());
        //注册栏目
        mMultiTypeAdapter.register(HomeAppGrids.class, new HomeAppGridsViewProvider());
        //注册每日一鲜
        mMultiTypeAdapter.register(HomeAppNotice.class, new HomeAppNoticeViewProvider());
        //注册商品列表标题
        mMultiTypeAdapter.register(HomeTopicTitle.class, new HomeTopicTitleViewProvider());
        //注册商品列表内容
        mMultiTypeAdapter.register(HomeTopicContent.class, new HomeTopicContentViewProvider(this));
        //注册商品更多
        mMultiTypeAdapter.register(HomeTopicMore.class, new HomeTopicMoreViewProvider());
        //注册魔方区域
        mMultiTypeAdapter.register(HomeAppMagic.class, new HomeAppMagicViewProvider());
        //注册商品横向列表内容
        //        mMultiTypeAdapter.register(HorizontalTopic.class, new HorizontalTopicViewProvider());
        mFab.setOnClickListener(v -> mRcvLoadMore.smoothScrollToPosition(0));
        mRcvLoadMore.setAdapter(mMultiTypeAdapter);
        //添加滑动监听事件
        mRcvLoadMore.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0 && getScrollYDistance() >= Utils.getScreenHeight() * 3 / 2) {
                    mFab.show();
                } else if (dy < 0) {
                    mFab.hide();
                }
                if (mToolbar.getHeight() == 0)
                    return;
                if (getScrollYDistance() >= mToolbar.getHeight() * 2) {
                    mTvLeft.setTextColor(getResources().getColor(R.color.color_333333));
                    mIvArrow.setImageResource(R.drawable.arrow_down_black);
                    mLlSearchBar.getDelegate().setBackgroundColor(getResources().getColor(R.color.color_D4D4D4_trans_70));
                } else {
                    mTvLeft.setTextColor(getResources().getColor(R.color.color_FFFFFF));
                    mIvArrow.setImageResource(R.drawable.arrow_down_white);
                    mLlSearchBar.getDelegate().setBackgroundColor(getResources().getColor(R.color.color_FFFFFF_trans_70));
                }
                if (getScrollYDistance() >= 0) {
                    try {
                        float toolBarAlpha = (((float) getScrollYDistance()) * 1.0f) / ((float) mToolbar.getHeight()) / 3;
                        if (toolBarAlpha > 1.0f) {
                            toolBarAlpha = 1.0f;
                        } else if (toolBarAlpha < 0.0f) {
                            toolBarAlpha = 0.0f;
                        }
                        String alpha = Integer.toHexString((int) (230.0f * toolBarAlpha));
                        if (alpha.length() < 2) {
                            alpha = "0" + alpha;
                        }
                        mToolbar.setBackgroundColor(Color.parseColor("#" + alpha + "FFFFFF"));
                        mHomeBottomLine.setBackgroundColor(Color.parseColor("#" + alpha + "E3E3E3"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }


        });
    }

    private int needToRequestNetDataTypeNum = 0;//需要通过请求网络获取数据的type数量

    private int requestTime = 0;//请求的次数

    private ErrorRunnable mErrorRunnable;

    private class ErrorRunnable implements Runnable {
        private LoadingViewCallback callback;


        public ErrorRunnable(LoadingViewCallback callback) {
            this.callback = callback;
        }

        @Override
        public void run() {
            if (callback != null)
                callback.showError();
        }
    }


    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        if (mToolbar != null)
            mToolbar.setVisibility(View.GONE);
        mRcvLoadMore.scrollToPosition(0);
        SupplierApi.getSupplierHome(mActivity, Utils.getSupplierId(), new RefreshAndLoadCallback<SupplierHome>(isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View v) {
                loadDataList(1, false);
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_GET_SHOPPING_CART_NUM));
            }

            @Override

            public boolean isShowContent() {
                return false;
            }

            @Override
            public void onResultSuccess(SupplierHome supplierHome, @Nullable Response response, LoadingViewCallback callback) {
                //超过25s还在加载数据 则显示加载失败视图 解决一直处理加载中的BUG
                if (!isPullToRefresh) {
                    if (mErrorRunnable != null) {
                        ThreadPool.getUiHandler().removeCallbacks(mErrorRunnable);
                    }
                    mErrorRunnable = new ErrorRunnable(callback);
                    ThreadPool.postOnUiDelayed(mErrorRunnable, 25000);
                }
                needToRequestNetDataTypeNum = 0;
                requestTime = 0;
                if (supplierHome != null) {
                    SupplierContent supplierContent = GsonConvert.fromDeserializerJson(supplierHome.getPageJson(), SupplierContent.class);
                    //搜索栏
                    if (!CheckUtils.isEmpty(supplierContent.getHeader())) {
                        if (!CheckUtils.isEmpty(supplierContent.getHeader().get(0).getData().getList())) {
                            hotList = supplierContent.getHeader().get(0).getData().getList();
                            mEditText.setHint(supplierContent.getHeader().get(0).getData().getList().get(0));
                            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_HOME_DATA_REFRESH, supplierContent.getHeader().get(0).getData().getList()));
                        }
                    }

                    /**
                     * 可排序组件
                     * 先确定有几种type需要另外请求数据
                     */

                    if (!CheckUtils.isEmpty(supplierContent.getSortable())) {
                        for (int i = 0; i < supplierContent.getSortable().size(); i++) {
                            BaseHomeData baseHomeData = supplierContent.getSortable().get(i);
                            if (baseHomeData != null && baseHomeData instanceof HomeAppListAOne) {
                                HomeAppListAOne.HomeAppListAOneData homeAppListAOneData = ((HomeAppListAOne) baseHomeData).getData();
                                if (homeAppListAOneData.getType() == 1) {
                                    needToRequestNetDataTypeNum++;
                                }
                            } else if (baseHomeData != null && baseHomeData instanceof HomeAppListATwoThree) {
                                HomeAppListATwoThree.HomeAppListATwoThreeData homeAppListATwoThreeData = ((HomeAppListATwoThree) baseHomeData).getData();
                                if (homeAppListATwoThreeData.getType() == 2 || homeAppListATwoThreeData.getType() == 3) {
                                    needToRequestNetDataTypeNum++;
                                }
                            }

                        }
                    }

                    CLog.i("num", "needToRequestNetDataTypeNum" + needToRequestNetDataTypeNum);
                    if (!CheckUtils.isEmpty(supplierContent.getSortable())) {
                        if (needToRequestNetDataTypeNum == 0) {
                            handleData(supplierContent.getSortable(), callback, isPullToRefresh);
                        } else {
                            /**
                             *
                             * 可排序组件
                             * 特殊type 进行网络请求
                             */


                            for (int i = 0; i < supplierContent.getSortable().size(); i++) {
                                final int a = i;
                                BaseHomeData baseHomeData = supplierContent.getSortable().get(i);
                                if (baseHomeData != null && baseHomeData instanceof HomeAppListAOne) {
                                    HomeAppListAOne.HomeAppListAOneData homeAppListAOneData = ((HomeAppListAOne) baseHomeData).getData();
                                    if (homeAppListAOneData.getType() == 1) {
                                        ThreadPool.postOnWorkerDelayed(() -> getGoodsList1(isPullToRefresh, a, supplierContent.getSortable(), homeAppListAOneData, (int) homeAppListAOneData.getId(), callback), 200);

                                    }
                                } else if (baseHomeData != null && baseHomeData instanceof HomeAppListATwoThree) {
                                    final int b = i;
                                    HomeAppListATwoThree.HomeAppListATwoThreeData homeAppListATwoThreeData = ((HomeAppListATwoThree) baseHomeData).getData();
                                    if (homeAppListATwoThreeData.getType() == 2 || homeAppListATwoThreeData.getType() == 3) {
                                        ThreadPool.postOnWorkerDelayed(() -> getGoodsList2(isPullToRefresh, b, supplierContent.getSortable(), homeAppListATwoThreeData, (int) homeAppListATwoThreeData.getId(), callback), 200);

                                    }
                                }

                            }
                        }
                    }


                } else {
                    if (mToolbar != null && !isPullToRefresh)
                        mToolbar.setVisibility(View.VISIBLE);
                    hotList.clear();
                    mEditText.setHint("");
                    callback.showEmpty();
                }

            }
        });
    }


    /**
     * type =1 type =1 时 调用分类的接口 {@link com.zhilianbao.leyaogo.http.api.CategoryApi#getGoodsList(Context, long, int, int, int, Callback)}
     *
     * @param pos
     * @param sortable
     * @param classifyId
     */
    private void getGoodsList1(boolean isPullToRefresh, int pos, List<BaseHomeData> sortable, HomeAppListAOne.HomeAppListAOneData homeAppListAOneData, int classifyId, LoadingViewCallback callback) {
        CLog.i("num", "getGoodsList1");
        CategoryApi.getHomeGoodsList(mActivity, Utils.getSupplierId(), classifyId, 1, pageSize, new JsonCallback<List<GoodsInfo>>(mActivity) {
            @Override
            public void onSuccess(List<GoodsInfo> o, Call call, Response response) {
                homeAppListAOneData.setList(o);
                ((HomeAppListAOne) sortable.get(pos)).setData(homeAppListAOneData);
                requestTime++;
                CLog.i("num", "requestTime" + requestTime);
                if (requestTime == needToRequestNetDataTypeNum) {
                    CLog.i("num", "requestTime == needToRequestNetDataTypeNum");
                    handleData(sortable, callback, isPullToRefresh);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                callback.showServerError();
                super.onError(call, response, e);

            }
        });
    }


    /**
     * AppListA type=0 时  处理skuMap
     */
    private List<SkuMapEntity> handleZeroSkuMap(List<HomeAppListATypeZeroInfo.AppListATypeZeroSku> skuMap) {
        List<SkuMapEntity> skuMapEntities = new ArrayList<>();
        for (HomeAppListATypeZeroInfo.AppListATypeZeroSku appListATypeZeroSku : skuMap) {
            SkuMapEntity skuMapEntity = new SkuMapEntity();
            skuMapEntity.setComments(appListATypeZeroSku.getComments());
            skuMapEntity.setGoodsId(appListATypeZeroSku.getGoodsId());
            skuMapEntity.setGoodsSkuMapId(appListATypeZeroSku.getGoodsSkuMapId());
            skuMapEntity.setSkuId(appListATypeZeroSku.getSkuId());
            skuMapEntity.setSkuName(appListATypeZeroSku.getSkuName());
            skuMapEntity.setStrVal1(appListATypeZeroSku.getStrVal1());
            skuMapEntity.setGoodsSkuMapItemResponse(GsonConvert.fromJson(appListATypeZeroSku.getGoodsSkuMapItemResponse(), new TypeToken<List<SkuMapEntity.GoodsSkuMapItemEntity>>() {
            }.getType()));
            skuMapEntities.add(skuMapEntity);
        }
        return skuMapEntities;
    }

    /**
     * 处理数据
     *
     * @param sortable
     */
    private void handleData(List<BaseHomeData> sortable, LoadingViewCallback callback, boolean isPullToRefresh) {
        mItems.clear();

        if (!CheckUtils.isEmpty(sortable)) {
            for (BaseHomeData baseHomeData : sortable) {

                if (baseHomeData != null) {


                    /**
                     * AppListA type =0
                     */
                    if (baseHomeData instanceof HomeAppListAZero) {
                        HomeAppListAZero.HomeAppListAZeroData homeAppListAZeroData = ((HomeAppListAZero) baseHomeData).getData();
                        if (!CheckUtils.isEmpty(homeAppListAZeroData.getList())) {
                            mItems.add(new HomeTopicTitle(homeAppListAZeroData.getTitle()));
                            for (int i = 0; i < homeAppListAZeroData.getList().size(); i++) {
                                HomeAppListATypeZeroInfo goodsInfo = homeAppListAZeroData.getList().get(i);
                                mItems.add(new HomeTopicContent(goodsInfo.getActivitySign(), 0, homeAppListAZeroData.getType(), goodsInfo.getGoodsPic(), String.valueOf(goodsInfo.getPrice()), String.valueOf(goodsInfo.getMPrice()), goodsInfo.getGoodsName(), goodsInfo.getGoodsDesc(), goodsInfo.getGoodsType(), goodsInfo.getGoodsSkuId(), goodsInfo.getSelectedSkuId(), goodsInfo.getSku(), goodsInfo.getSkuMap() != null ? handleZeroSkuMap(goodsInfo.getSkuMap()) : null, goodsInfo.getGoodsId(), goodsInfo.getShopId(), goodsInfo.getItemVals(), goodsInfo.getSkuMPrice() + "", goodsInfo.getSkuPrice() + "", ""));
                            }
                            //                        if (homeAppListAZeroData.getList().size() > homeAppListAZeroData.getShowNumber()) {
                            //                            mItems.add(new HomeTopicMore(homeAppListAZeroData.getType(),0,homeAppListAZeroData.getTitle()));
                            //                        }
                        }

                    }

                    /**
                     * AppListA type =1
                     */
                    else if (baseHomeData instanceof HomeAppListAOne) {
                        HomeAppListAOne.HomeAppListAOneData homeAppListAOneData = ((HomeAppListAOne) baseHomeData).getData();
                        if (!CheckUtils.isEmpty(homeAppListAOneData.getList())) {
                            mItems.add(new HomeTopicTitle(homeAppListAOneData.getTitle()));
                            for (int i = 0; i < Math.min(homeAppListAOneData.getList().size(), homeAppListAOneData.getShowNumber()); i++) {
                                GoodsInfo goodsInfo = homeAppListAOneData.getList().get(i);
                                mItems.add(new HomeTopicContent(goodsInfo.getActivitySign(), 0, homeAppListAOneData.getType(), goodsInfo.getGoodsPic(), String.valueOf(goodsInfo.getPrice()), String.valueOf(goodsInfo.getMPrice()), goodsInfo.getGoodsName(), goodsInfo.getGoodsDesc(), goodsInfo.getGoodsType(), goodsInfo.getGoodsSkuId(), goodsInfo.getSelectedSkuId(), goodsInfo.getSku(), goodsInfo.getSkuMap(), goodsInfo.getGoodsId(), goodsInfo.getShopId(), goodsInfo.getItemVals(), goodsInfo.getSkuMPrice() + "", goodsInfo.getSkuPrice() + "", ""));
                            }
                            if (homeAppListAOneData.getList().size() > homeAppListAOneData.getShowNumber()) {
                                mItems.add(new HomeTopicMore(homeAppListAOneData.getType(), homeAppListAOneData.getId(), homeAppListAOneData.getTitle()));
                            }
                        }


                    }
                    /**
                     *
                     * AppListA type =2 或 type =3
                     */
                    else if (baseHomeData instanceof HomeAppListATwoThree) {
                        HomeAppListATwoThree.HomeAppListATwoThreeData homeAppListATwoThreeData = ((HomeAppListATwoThree) baseHomeData).getData();
                        if (!CheckUtils.isEmpty(homeAppListATwoThreeData.getList())) {
                            mItems.add(new HomeTopicTitle(homeAppListATwoThreeData.getTitle()));
                            for (int i = 0; i < Math.min(homeAppListATwoThreeData.getList().size(), homeAppListATwoThreeData.getShowNumber()); i++) {
                                SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean goodsInfo = homeAppListATwoThreeData.getList().get(i);
                                mItems.add(new HomeTopicContent(goodsInfo.getGoodsActivitySign(), (int) goodsInfo.getPriceType(), homeAppListATwoThreeData.getType(), goodsInfo.getGoodsPic(), String.valueOf(goodsInfo.getPrice()), String.valueOf(goodsInfo.getMPrice()), goodsInfo.getGoodsName(), goodsInfo.getGoodsDesc(), goodsInfo.getGoodsType(), (int) goodsInfo.getGoodsSkuId(), 0, null, null, (int) goodsInfo.getGoodsId(), (int) goodsInfo.getShopId(), goodsInfo.getItemVals(), goodsInfo.getSkuMPrice() + "", goodsInfo.getSkuPrice() + "", goodsInfo.getGoodsPrice() + ""));
                            }
                            if (homeAppListATwoThreeData.getList().size() > homeAppListATwoThreeData.getShowNumber()) {
                                mItems.add(new HomeTopicMore(homeAppListATwoThreeData.getType(), homeAppListATwoThreeData.getId(), ""));
                            }
                        }
                    }
                    /**
                     *  appSlider appGirds appNotice appMagic
                     */
                    else if (baseHomeData instanceof HomeAppSlider) {
                        if (!CheckUtils.isEmpty(((HomeAppSlider) baseHomeData).getData().getList()))
                            mItems.add(baseHomeData);
                    } else if (baseHomeData instanceof HomeAppGrids) {
                        if (!CheckUtils.isEmpty(((HomeAppGrids) baseHomeData).getData().getList()))
                            mItems.add(baseHomeData);
                    } else if (baseHomeData instanceof HomeAppNotice) {
                        if (!CheckUtils.isEmpty(((HomeAppNotice) baseHomeData).getData().getList()))
                            mItems.add(baseHomeData);
                    } else if (baseHomeData instanceof HomeAppMagic) {
                        if (!CheckUtils.isEmpty(((HomeAppMagic) baseHomeData).getData().getList()))
                            mItems.add(baseHomeData);
                    }
                }
            }
            if (mItems.size() == 0) {
                callback.showEmpty();
            } else {
                callback.showContent();
            }
            mMultiTypeAdapter.notifyDataSetChanged();
            heightArray = new int[mItems.size()];

        } else {
            callback.showEmpty();
        }
        if (mToolbar != null && !isPullToRefresh)
            mToolbar.setVisibility(View.VISIBLE);

    }

    /**
     * type=2 和 type=3时调用活动专题的接口 {@link com.zhilianbao.leyaogo.http.api.ActivityApi#getActivityDetails(Context, long, int, int, Callback)}
     *
     * @param pos
     * @param sortable
     * @param activityId
     */
    private void getGoodsList2(boolean isPullToRefresh, int pos, List<BaseHomeData> sortable, HomeAppListATwoThree.HomeAppListATwoThreeData homeAppListATwoThreeData, int activityId, LoadingViewCallback callback) {
        CLog.i("num", "getGoodsList2");
        ActivityApi.getActivityDetails(mActivity, activityId, 1, pageSize, new JsonCallback<SpecialActivityInfo>(mActivity) {
            @Override
            public void onSuccess(SpecialActivityInfo specialActivityInfo, Call call, Response response) {
                List<SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean> goodsListBeen = new ArrayList<>();
                for (SpecialActivityInfo.MallActivityGoodsSignVoListBean mallActivityGoodsSignVoListBean : specialActivityInfo.getMallActivityGoodsSignVoList()) {
                    for (SpecialActivityInfo.MallActivityGoodsSignVoListBean.ActivityGoodsListBean activityGoodsListBean : mallActivityGoodsSignVoListBean.getActivityGoodsList()) {
                        goodsListBeen.add(activityGoodsListBean);
                    }
                }
                homeAppListATwoThreeData.setList(goodsListBeen);
                ((HomeAppListATwoThree) sortable.get(pos)).setData(homeAppListATwoThreeData);
                requestTime++;
                CLog.i("num", "requestTime" + requestTime);
                if (requestTime == needToRequestNetDataTypeNum) {
                    CLog.i("num", "requestTime == needToRequestNetDataTypeNum");
                    handleData(sortable, callback, isPullToRefresh);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                callback.showServerError();
                super.onError(call, response, e);

            }
        });
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public MultiTypeAdapter getMultiAdapter() {
        return mMultiTypeAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }

    @Override
    public void onLoadMore() {
        loadDataList(mCurPage, true);
    }

    @Override
    public void onRefresh() {
        loadDataList(1, true);
    }

    @Override
    public void onUIScrollChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
        super.onUIScrollChange(frame, isUnderTouch, status, ptrIndicator);
        if (ptrIndicator.getCurrentPosY() > 0) {
            setHomeToolbarCanClick(false);
            if (mToolbar != null && mToolbar.getVisibility() != View.GONE && !isAnimating) {
                showToolbarAnimation(false);
            }
        } else {
            setHomeToolbarCanClick(true);
            if (mToolbar != null && mToolbar.getVisibility() != View.VISIBLE && !isAnimating) {
                showToolbarAnimation(true);
            }

        }
    }

    private boolean isAnimating;

    /**
     * 动态显示状态栏
     *
     * @param show
     */
    private void showToolbarAnimation(boolean show) {
        Animation alphaAnim = new AlphaAnimation(show ? 0 : 1f, show ? 1f : 0);
        alphaAnim.setDuration(120);
        alphaAnim.setFillAfter(true);
        alphaAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isAnimating = true;
                if (show) {
                    mToolbar.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isAnimating = false;
                if (!show)
                    mToolbar.setVisibility(View.GONE);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mToolbar.startAnimation(alphaAnim);
    }
    /**
     * 检测搜索栏区域 解决快速滑动到顶部(搜索栏隐藏动画还没执行结束的时候)搜索栏不显示的BUG
     */
    //    private void checkSearchZone() {
    //        LinearLayoutManager layoutManager = (LinearLayoutManager) mRcvLoadMore.getLayoutManager();
    //        int pos = layoutManager.findFirstCompletelyVisibleItemPosition();
    //        if (pos == 0) {
    //            showSearchZone(false);
    //        }
    //    }


    /**
     * 显示搜索栏
     *
     * @param needAnimation 是否显示动画
     */
    //    private void showSearchZone(boolean needAnimation) {
    //        if (mLlSearchZone != null && mLlSearchZone.getVisibility() != View.VISIBLE) {
    //            if (needAnimation) {
    //                if (mSearchShowAnim != null && !mIsAnimating) {
    //                    mLlSearchZone.startAnimation(mSearchShowAnim);
    //                }
    //            } else if (mLlSearchZone != null) {
    //                mLlSearchZone.setVisibility(View.VISIBLE);
    //            }
    //        }
    //    }

    /**
     * 隐藏搜索栏
     *
     * @param needAnimation 是否需要动画
     */
    //    private void goneSearchZone(boolean needAnimation) {
    //        if (mLlSearchZone != null && mLlSearchZone.getVisibility() != View.GONE) {
    //            if (needAnimation) {
    //                if (mSearchGoneAnim != null && !mIsAnimating) {
    //                    mLlSearchZone.startAnimation(mSearchGoneAnim);
    //                }
    //            } else if (mLlSearchZone != null) {
    //                mLlSearchZone.setVisibility(View.GONE);
    //            }
    //        }
    //    }

    /**
     * 获取recyclerView 滑动的 Y 距离
     *
     * @return
     */
    public int getScrollYDistance() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) mRcvLoadMore.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisibleChildView = layoutManager.findViewByPosition(position);
        int itemHeight = 0;
        if (firstVisibleChildView != null) {
            heightArray[position] = firstVisibleChildView.getHeight();
            for (int i = 0; i < position; i++) {
                itemHeight += heightArray[i];
            }
            return itemHeight - firstVisibleChildView.getTop() /*+ (position > 0 ? mRcvLoadMore.getHeaderAndFooterRecyclerViewAdapter().getFirstHeader().getHeight() : 0)*/;
        }
        return 0;
    }


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_home;
    }


    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            //            //首次进入应用 没选择城市 返回  默认 定位 深圳市 运营商 云鲜生
            //            case LeEventCode.MSG_CODE_LOCATION_BACK:
            //                Utils.putLocation(getString(R.string.default_city));
            //                if (mTvLeft != null) {
            //                    mTvLeft.setText(getString(R.string.default_city));
            //                }
            //                showDefaultAddressDialog();
            //                break;

            case LeEventCode.MSG_CODE_SELECT_OPERATOR:
                String address = (String) eventManager.getData();
                if (!CheckUtils.isEmpty(address)) {
                    Utils.putLocation(address);
                    if (mTvLeft != null) {
                        mTvLeft.setText(address);
                    }
                }

                //                if (mItems.size() == 0) {
                loadDataList(1, false);
                mFab.hide(false);
                //                } else {
                //                    loadDataList(1, true);
                //                }

                break;
        }
        //百度定位返回结果
        //        if (eventManager.getEventCode() == UserEventCode.MSG_CODE_BAIDU_LOCATION) {
        //            mLocation = (String) eventManager.getData();
        //            if (!CheckUtils.isEmpty(mLocation) && mToolbar != null && mTvLeft != null) {
        //                mTvLeft.setText(Utils.getLocationWithoutSuffix(mLocation));
        //                Utils.putLocation(mLocation);
        //
        //            }
        //
        //        }
    }

    @Override
    public void searchBarClick() {
        super.searchBarClick();
        Bundle bundle = new Bundle();
        bundle.putSerializable(IntentConfig.HOT_SEARCH_LIST, (Serializable) hotList);
        Utils.startActivity(mActivity, SearchActivity.class, bundle);
    }

    @Override
    public void btnLeftTextClick() {
        super.btnLeftTextClick();
        Utils.startActivity(mActivity, SelectSupplierActivity.class);
    }

    @Override
    public void onAddToCartClick(HomeTopicContent item, ImageView imageView) {
        if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
            showSpecPop(item, imageView);
        } else {
            LogicCodeBlock.create().registerLogicCodeCallback(logicState -> {
                if (logicState == LogicCodeBlock.LogicState.AddToCart.value)
                    showSpecPop(item, imageView);
            });
        }
    }

    /**
     * 显示规格选弹框
     *
     * @param goodsInfo
     * @param imageView
     */
    private void showSpecPop(HomeTopicContent goodsInfo, ImageView imageView) {
        if (Utils.isShowSpePop(goodsInfo.getGoodsType(), goodsInfo.getGoodSkuId())) {

            Utils.showSpecPop(mActivity, getView(), 1, goodsInfo.getGoodsPic(), goodsInfo.getGoodSkuId(), goodsInfo.getSelectSkuId(), goodsInfo.getSkuEntities(), goodsInfo.getSkuMapEntities(), new GoodsSpecPopUtils.OnPopClickListener() {
                @Override
                public void onAddToCart(View v, int goodsSkuId) {
                    // 设置gooSkuId
                    goodsInfo.setGoodSkuId(goodsSkuId);
                    addToCart(goodsInfo, imageView);
                    //重置goodsSkuId
                    goodsInfo.setGoodSkuId(0);
                }

                @Override
                public void onSpecSelect(SkuEntity skuEntity) {
                    goodsInfo.setSelectSkuId(skuEntity.getGoodsSkuId());
                }
            });

        } else {// 不是sku商品，或是sku商品但是后台根据sku的类型分类成多个商品返回出来
            addToCart(goodsInfo, imageView);
        }

    }

    /**
     * 加入购物车
     *
     * @param goodsInfo
     */
    private void addToCart(HomeTopicContent goodsInfo, ImageView imageView) {
        CategoryApi.addToShoppingCart(mActivity, (int) Utils.getUserLoginInfo().getUserId(), goodsInfo.getGoodsId(), (int) Utils.getSupplierId(), goodsInfo.getShopId(), goodsInfo.getGoodSkuId(), 1, 0, new DialogCallback<GoodsStock>(mActivity) {

            @Override
            public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                ShopAnimationUtils.addToShoppingCart(mActivity, 1, imageView, ((MainActivity) mActivity).getShopTabView(), ((MainActivity) mActivity).getRlContent(), false, new ShopAnimationUtils.IAnimEndListener() {
                    @Override
                    public void onAnimEnd() {
                        XToastUtils.showShortToast(R.string.msg_add_to_shoppingCart_sucs);
                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                    }
                });
            }
        });
    }

    @Override
    public boolean isStatusDarkMode() {
        return true;
    }

}
